package covertjava.chat;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * <p>Main window of Chat</p>
 * <p>Copyright: Copyright (c) 2004 Sams Publishing</p>
 * @author Alex Kalinovsky
 * @version 1.0
 */
public class MainFrame extends JFrame implements ActionListener, MessageListener {

    JPanel contentPane;
    JMenuBar menuBar = new JMenuBar();
    JMenu menuFile = new JMenu();
    JMenuItem menuFileExit = new JMenuItem();
    JMenu jMenuHelp = new JMenu();
    JMenuItem menuHelpAbout = new JMenuItem();
    JToolBar toolBar = new JToolBar();
    JButton btnSend = new JButton();
    JButton btnHelp = new JButton();
    ImageIcon imageSend;
    ImageIcon imageHelp;
    JLabel statusBar = new JLabel();
    BorderLayout borderLayout = new BorderLayout();
    JSplitPane splitPane = new JSplitPane();
    JMenuItem menuEditSend = new JMenuItem();
    JComboBox cmbhostName = new JComboBox();
    JLabel lblhostName = new JLabel();
    Component filler;
    JScrollPane scrollPaneTop = new JScrollPane();
    JScrollPane scrollPaneBottom = new JScrollPane();
    JTextArea txtMessage = new JTextArea();
    JEditorPane txtConversation = new JEditorPane();
    StringBuffer conversation = new StringBuffer(300);

    /**Construct the frame*/
    public MainFrame() throws Exception {
        this(true);
    }

    public MainFrame(boolean initChatServer) throws Exception {
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        this.conversation.append("<HTML><BODY>");
        jbInit();

        if (initChatServer == true) {
            ChatServer.getInstance().init();
            ChatServer.getInstance().setMessageListener(this);
        }
    }

    /**Component initialization*/
    private void jbInit() throws Exception {
        imageSend = new ImageIcon(MainFrame.class.getResource("images/saturn_button.gif"));
        imageHelp = new ImageIcon(MainFrame.class.getResource("images/help_button.gif"));
        filler = Box.createVerticalStrut(1);
        setIconImage(Toolkit.getDefaultToolkit().createImage(MainFrame.class.getResource("images/saturn_small.jpg")));
        contentPane = (JPanel) this.getContentPane();
        contentPane.setLayout(borderLayout);
        this.setSize(new Dimension(400, 300));
        this.setTitle("Chat Application");
        statusBar.setText(" ");
        menuFile.setText("File");
        menuFileExit.setText("Exit");
        menuFileExit.addActionListener(this);
        jMenuHelp.setText("Help");
        menuHelpAbout.setText("About");
        menuHelpAbout.addActionListener(this);
        btnSend.addActionListener(this);
        btnSend.setIcon(imageSend);
        btnSend.setBorder(BorderFactory.createEtchedBorder());
        btnSend.setMaximumSize(new Dimension(27, 27));
        btnSend.setMinimumSize(new Dimension(27, 27));
        btnSend.setPreferredSize(new Dimension(27, 27));
        btnSend.setToolTipText("Send message");
        btnHelp.setIcon(imageHelp);
        btnHelp.addActionListener(this);
        btnHelp.setBorder(BorderFactory.createEtchedBorder());
        btnHelp.setMaximumSize(new Dimension(27, 27));
        btnHelp.setMinimumSize(new Dimension(27, 27));
        btnHelp.setPreferredSize(new Dimension(27, 27));
        btnHelp.setToolTipText("Help");
        splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
        splitPane.setContinuousLayout(true);
        menuEditSend.setText("Send message");
        menuEditSend.addActionListener(this);
        lblhostName.setText("Host Name: ");
        txtMessage.setLineWrap(true);
        txtMessage.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    e.consume();
                    doSendMessage();
                }
            }
        });
        txtConversation.setEditable(false);
        txtConversation.setContentType("text/html");
        scrollPaneBottom.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        cmbhostName.setEditable(true);
        toolBar.add(lblhostName, null);
        toolBar.add(cmbhostName, null);
        toolBar.add(btnSend);
        toolBar.add(filler, null);
        toolBar.add(btnHelp);
        menuFile.add(menuEditSend);
        menuFile.addSeparator();
        menuFile.add(menuFileExit);
        jMenuHelp.add(menuHelpAbout);
        menuBar.add(menuFile);
        menuBar.add(jMenuHelp);
        this.setJMenuBar(menuBar);
        contentPane.add(toolBar, BorderLayout.NORTH);
        contentPane.add(statusBar, BorderLayout.SOUTH);
        contentPane.add(splitPane, BorderLayout.CENTER);
        splitPane.add(scrollPaneTop, JSplitPane.TOP);
        splitPane.add(scrollPaneBottom, JSplitPane.BOTTOM);
        scrollPaneBottom.getViewport().add(txtMessage, null);
        scrollPaneTop.getViewport().add(txtConversation, null);
        splitPane.setDividerLocation(160);
    }

    /**File | Exit action performed*/
    public void doExit(ActionEvent e) {
        System.exit(0);
    }

    /**Help | About action performed*/
    void doShowHelp() {
        AboutDialog dlg = new AboutDialog(this);
        Dimension dlgSize = dlg.getPreferredSize();
        Dimension frmSize = getSize();
        Point loc = getLocation();
        dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
        dlg.setModal(true);
        dlg.show();
    }

    /**Overridden so we can exit when window is closed*/
    protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            doExit(null);
        }
    }

    /**
     * Sends a message to the specified user
     */
    void doSendMessage() {
        try {
            String host = this.cmbhostName.getEditor().getItem().toString();
            String message = this.txtMessage.getText();
            ChatServer.getInstance().sendMessage(host, message);
            appendMessage(message, null);
            this.txtMessage.setText("");
        } catch (Exception x) {
            x.printStackTrace();
            JOptionPane.showMessageDialog(this, x.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    /*synchronized*/ void appendMessage(String message, MessageInfo messageInfo) {

        if (messageInfo == null) {
            this.conversation.append("<font color=\"red\">");
            this.conversation.append("You");
        }
        else {
            this.conversation.append("<font color=\"blue\">");
            this.conversation.append(messageInfo.getDisplayName());
        }
        this.conversation.append(": ");
        this.conversation.append("</font>");

        this.conversation.append(message);
        this.conversation.append("<br>");
        this.txtConversation.setText(this.conversation.toString() + "</BODY></HTML>");
    }

    /**
     * Called when a new message is received
     */
    public void messageReceived(String message, MessageInfo messageInfo) {
        appendMessage(message, messageInfo);
    }

    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == this.menuEditSend || event.getSource() == this.btnSend) {
            doSendMessage();
        }
        else if (event.getSource() == this.menuHelpAbout || event.getSource() == this.btnHelp) {
            doShowHelp();
        }
    }
}
